// pages/user/withdrawLog.js
import Datetime from '../../utils/datetime'
import request from '../../utils/request'

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeIndex: 0,
    dataList: [{}, {}, {}, {}]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initData()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.loadMore()
  },

  /*
   * 切换分类
   */
  switchCatalog: function (e) {
    let index = parseInt(e.currentTarget.dataset.index)
    this.setData({
      activeIndex: index
    })
    if (index > 0) {
      this.initData()
    }
  },

  /*
   * 初始化打赏列表数据
   */
  initData(callback) {
    let that = this
    let activeIndex = this.data.activeIndex
    let dataList = this.data.dataList
    let activeData = dataList[activeIndex]
    if (activeData.count) {
      return
    }
    let params = {}
    if (activeIndex) {
      params.status = activeIndex - 1
    }
    wx.showLoading({
      title: '加载中',
    })
    let url = app.globalData.apiHost + '/albums/withdraws/'
    request(url, 'GET', app.globalData.loginToken, params, function (err, data) {
      console.log(data)
      wx.hideLoading()
      if (!err) {
        that._setDatetime(data)
        dataList[activeIndex] = data
        that.setData({ dataList: dataList })
      }
    })
  },


  /*
   * 加载更多数据
   */
  loadMore() {
    let that = this
    let activeIndex = this.data.activeIndex
    let dataList = this.data.dataList
    let activeData = dataList[activeIndex]
    if (activeData.next) {
      request(activeData.next, 'GET', app.globalData.loginToken, {}, function (err, data) {
        if (!err) {
          that._setDatetime(data)
          activeData.next = data.next
          activeData.previous = data.previous
          activeData.results = activeData.results.concat(data.results)
          that.setData({ dataList: dataList })
        }
      })
    }
  },

  /*
   * 操作时间
   */
  _setDatetime(data) {
    for (let i = 0; i < data.results.length; i++) {
      let item = data.results[i]
      let datetime = new Datetime(item.created)
      item.createTime = datetime.getDatetimeStr()
    }
  }

})